package com.swak.monitor.flux.service;

import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.swak.Constants;
import com.swak.OS;
import com.swak.registry.NotifyListener;
import com.swak.registry.RegistryService;
import com.swak.registry.URL;
import com.swak.utils.Maps;
import com.swak.utils.Sets;

@Service
public class FluxMonitorService implements InitializingBean, DisposableBean, NotifyListener {

	private URL url;

	@Autowired(required = false)
	private RegistryService registryService;

	private final Map<String, Set<String>> cache;

	public FluxMonitorService() {
		cache = Maps.newConcurrentMap();
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		if (this.registryService != null) {
			Map<String, String> parameters = Maps.newHashMap();
			parameters.put(Constants.Application_KEY, registryService.applicationName());
			parameters.put(Constants.Service_Key, Constants.Subscribe_Any_Value);
			parameters.put(Constants.Category_Key,
					Constants.Registry_Flux_Api_Key + Constants.IDS_SEPARATE + Constants.Registry_Flux_Service_Key);
			this.url = new URL(Constants.Registry_Flux_Key, OS.ip(), 0, parameters);
			this.registryService.subscribe(this.url, this);
		}
	}

	@Override
	public void destroy() throws Exception {
		if (this.registryService != null) {
			this.registryService.unsubscribe(this.url, this);
		}
	}

	@Override
	public void notify(List<URL> urls) {
		for (URL url : urls) {
			String service = url.getService();
			Set<String> services = cache.computeIfAbsent(service, (k) -> {
				return Sets.newConcurrentSet();
			});
			services.add(url.toFullString());
		}
	}

	/**
	 * 服务列表
	 * 
	 * @return
	 */
	public Set<String> apis() {
		return cache.keySet();
	}

	/**
	 * 服务列表
	 * 
	 * @return
	 */
	public Set<String> services(String service) {
		return cache.get(service);
	}
}